﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;

namespace FACUI.frmDialog
{
    //自定义事件
    public delegate void MyOwnerEventHandler(Object sender, MsgEventArgs e);
    public class MsgEventArgs : EventArgs
    {
        private ulong _index = 0;
        public ulong CurIndex
        {
            get { return _index; }
            set { _index = value; }
        }
        private byte[] _bufMsg;
        public byte[] BufMsg
        {
            get { return _bufMsg; }
            set
            {
                if (value.Length > 0)
                {
                    _bufMsg = new byte[value.Length];
                    Buffer.BlockCopy(value, 0, _bufMsg, 0, value.Length);
                }
            }
        }

        private double[] d_bufMsg;
        public double[] dBufMsg
        {
            get { return d_bufMsg; }
            set
            {
                if (value.Length > 0)
                {
                    d_bufMsg = new double[value.Length];
                    Buffer.BlockCopy(value, 0, d_bufMsg, 0, value.Length);
                }
            }
        }
    }
 
    public class TransDataToCore
    {

        //心跳线程
        private UdpClient udpHeart = null;
        //数据收发线程
        private UdpClient udpData = null;
        //心跳时间间隔（ms）
        private const int HEARTSPAN = 50;
        //心跳数包
        private byte[] HeartBytes = new byte[] { 0xA0, 0xA0, 0x01, 0x00, 0x02, 0x0A, 0x0A };
        //记轴数据包
        private byte[] AxesBytes = new byte[14];

        public void SendHeart()
        {
            DateTime dt = DateTime.Now;
            SendData(0,0,0,0);
            while (true)
            {
                try
                {
                    if (dt.AddMilliseconds(HEARTSPAN) <= DateTime.Now)
                    {
                        dt = DateTime.Now;
                        UdpSend(HeartBytes);
                    }
                }
                catch (Exception ex) { System.Diagnostics.Debug.WriteLine( string.Format("{0}  {1}:{2}\r\n", DateTime.Now, ex.StackTrace, ex.Message)); }
                Thread.Sleep(100);
            }
        }
        /// <summary>
        /// 发送区间占用情况数据
        /// </summary>
        /// <param name="ZNo">区段号</param>
        /// <param name="Aaxes">A点轴数</param>
        /// <param name="Baxes">B点轴数</param>
        /// <param name="Zstate">区间占用状态</param>
        public void SendData(int ZNo, int Aaxes, int Baxes, int Zstate)
        {
            try
            {
                Array.Clear(AxesBytes, 0, AxesBytes.Length);
                //开始标志
                AxesBytes[0] = 0xA0;
                AxesBytes[1] = 0xA0;
                //长度
                AxesBytes[2] = 10;
                AxesBytes[3] = 0;
                //命令
                AxesBytes[4] = 1;
                //区段号
                AxesBytes[5] = (byte)(ZNo & 0xFF);
                AxesBytes[6] = (byte)((ZNo >> 8) & 0xFF);
                //A轴轴数
                AxesBytes[7] = (byte)(Aaxes & 0xFF);
                AxesBytes[8] = (byte)((Aaxes >> 8) & 0xFF);
                //B轴轴数
                AxesBytes[9] = (byte)(Baxes & 0xFF);
                AxesBytes[10] = (byte)((Baxes >> 8) & 0xFF);
                //状态
                AxesBytes[11] = (byte)(Zstate & 0xFF);
                //结束标志
                AxesBytes[12] = 0x0A;
                AxesBytes[13] = 0x0A;

                UdpSend(AxesBytes);
            }
            catch { }
        }

        private void UdpSend(byte[] bytes)
        {
            try
            {
                if (udpHeart == null)
                {
                    udpHeart = new UdpClient();
                    udpHeart.Connect(IPAddress.Parse(CSource.RecCoreBoardAddr), CSource.SendCoreBoardPort);
                }
                udpHeart.Send(bytes, bytes.Length);
            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message); }
        }

        public event MyOwnerEventHandler ReceiveDataFromHeartThreadEvent;
        public void UdpReceive(object O)
        {
            DateTime dt = DateTime.Now;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9090);
            while (true)
            {
                try
                {
                    if (udpData == null)
                    {
                        udpData = new UdpClient(CSource.RecCoreBoardPort);
                    }
                    byte[] bytes = udpData.Receive(ref ipep);
                    if (Encoding.Default.GetString(bytes) == "zero")
                    {
                        SendData(0,0,0,0);
                        if (ReceiveDataFromHeartThreadEvent != null)
                        {
                            ReceiveDataFromHeartThreadEvent(null, new MsgEventArgs());
                        }
                    }
                }
                catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message); }
            }
        }
    }
}
